package com.jifeng.br.pjj.bookreader.util.shiro;

import com.jifeng.br.pjj.bookreader.entity.TokenEntity;
import com.jifeng.br.pjj.bookreader.entity.UserinfoEntity;
import com.jifeng.br.pjj.bookreader.service.TokenService;
import com.jifeng.br.pjj.bookreader.service.UserinfoService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author PangJunjie
 * @Date 2023/7/12/012
 */
@Component
public class Shiro2Realm extends AuthorizingRealm {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private UserinfoService userinfoService;

    /*验证权限*/
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return new SimpleAuthorizationInfo();
    }

    /*验证token是否有效*/
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        /*获取token*/
        String token = (String) authenticationToken.getPrincipal();
        /*获取token实体类*/
        TokenEntity tokenEntity = tokenService.getByToken(token);
        /*获取当前登录用户信息*/
        UserinfoEntity loginInfo = userinfoService.getById(tokenEntity.getUserId());
        return new SimpleAuthenticationInfo(loginInfo, token, getName());
    }

    /*
     * 重写supports使自定义token生效
     * */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof Shiro2Token;
    }
}
